<template>
  <el-dialog v-model="addDialog" title="课程添加" width="800">
    <el-form
        ref="addFormRef"
        id="form"
        :model="addFormData"
        :rules="subjectRules"
        label-width="auto"
        class="demo-infoForm"
    >
      <el-form-item label="课程名称" label-width="80" prop="subjectName">
        <el-input v-model="addFormData.subjectName"/>
      </el-form-item>
      <el-form-item label="课程描述" label-width="80" prop="subjectDescription">
        <el-input v-model="addFormData.subjectDescription"/>
      </el-form-item>

    </el-form>
    <template #footer>

      <div class="dialog-footer">
        <el-button @click="addDialog = false">关闭</el-button>
        <el-button @click="submitForm(addFormRef)" type="primary" :disabled="!addFormData.subjectName || !addFormData.subjectDescription">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {defineModel} from "@vue/runtime-core";
import {reactive} from "@vue/reactivity";
import axios from "@/axios/index.js";
import {ElMessage} from "element-plus";
import {ref} from "vue";

let addDialog = defineModel('addDialog')
const emit = defineEmits(['initData'])

let addFormRef = ref()

/**
 *  表单数据对象
 * @type {{subjectName: string, subjectDescription: string, creatorId: string}}
 */
const addFormData = ref({
  subjectName: '',
  subjectDescription: '',
  creatorId: '',
})

//用户添加表单校验规则
const subjectRules = reactive({
  subjectName: [
    {required: true, message: '请输入课程名称', trigger: 'blur'},
    {min: 1, max: 10, message: '长度在 1 到 10 个字符'},
  ],
  subjectDescription: [
    {required: true, message: '请输入课程描述', trigger: 'blur'},
    {min: 3, max: 20, message: '长度在 3 到 20 个字符'},
  ],
})

//添加课程
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios.post('/api/v1/admin/subject', {
        subjectName: addFormData.value.subjectName,
        subjectDescription: addFormData.value.subjectDescription,
        creatorId: addFormData.value.creatorId,
      }).then(resp => {
        emit('initData')
        ElMessage({
          message: resp.data.message,
          type: 'success',
          duration: 1500
        })
        addDialog.value = false
      })
      addDialog.value = false
    }
  })
}
</script>

<style scoped>

</style>